//
// Created by hunan on 25-3-29.
//

#include "public_module/loop_module/loop.h"
#include "public_module/protocol_connection/http_protocol_operation.h"
#include "public_module/protocol_connection/protocol_connection.h"
#include "public_module/protocol_connection/protocol_operation.h"
#include <string>
#include <unistd.h>
#include <public_module/file_module/file_description.h>
#include <public_module/file_module/file_handle.h>
#include <public_module/http_protocol/http_protocol_msg.h>



int main(int argc, const char * argv[])
{
    std::string url = "https://filesamples.com/samples/video/flv/sample_960x540.flv";
    Loop loop;
    HttpProtocolOperation operate(HttpProtocolOperation::RESPONSE);
    ProtocolConnection connection(&loop, &operate);
    connection.OnProtocolConnect([&operate](ProtocolConnection * connection, int) {

        printf("connected will send http request.\n");
        auto request = operate.HttpRequestMsg();
        auto protocol = connection->ProtocolData();
        request->AddHeaderLine("GET", protocol.m_uri, "HTTP/1.1");
        request->AddHeaderSign("Host", protocol.m_host);
        std::string content;
        request->String(content);
        connection->SendMessage((const uint8_t*)content.data(), content.length());
    });
    connection.OnProtocolMessage([](ProtocolConnection * connection, ProtocolOperation * operation) {

        auto * http_operate = (HttpProtocolOperation*)operation;
        std::string file = "download_" + std::to_string(time(nullptr)) + ".txt";
        FileHandle h(file);
        h.OpenFileAppendWrite();
        h.Write(http_operate->HttpResponseMsg()->Body().data(), http_operate->HttpResponseMsg()->Body().size());
        printf("finish.\n");
    });
    connection.OnProtocolDisConn([](ProtocolConnection * connection, int result) {

        exit(-1);
    });
    connection.InitServerUrl(url, {.m_ssl_key_log_file = "ssl_key_log_file.txt"});
    loop.Run();
    return 0;
}
